// pagesShangping/pages/submitOrder/index.js
const app = getApp();
import { baseUrl } from "../../../api/request";
import { getStorage } from "../../../utils/localStorage";
import { consignee_Info, unifiedOrderPlacement, order_Create, paymentSuccessCallback } from "../../../api/shopping"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        baseUrl: baseUrl,
        //自定义导航栏参数
        navData: {
            title: '提交订单',
            level: 2 //导航栏级别  
        },
        userInfo: {},
        pageTop: app.globalData.navHeight + app.globalData.navTop,
        pageBottom: app.globalData.bottomLift,
        buttonStates: false,
        list: [],
        consigneeData: {},
        totalPrice: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({ userInfo: getStorage('user') });
        if (JSON.stringify(options) !== "{}") {
            const data = JSON.parse(decodeURIComponent(options.data));
            const arr = data.shopCartList.map(item => ({
                ...item,
                imageScale: item.imageScale ? item.imageScale.split(",") : []
            }));
            this.setData({ list: arr, totalPrice: data.price });
        } else {
            wx.showToast({
                icon: 'none',
                title: '获取页面参数失败',
                duration: 2000
            })
        };
        this.getConsigneeInfo();
    },

    /**
 * 生命周期函数--监听页面显示
 */
    onShow(e) {
        var pages = getCurrentPages(),
            currPage = pages[pages.length - 1]; //当前页面
        let addressData = currPage.data.addressData;
        if (addressData) {
            this.setData({ consigneeData: addressData })
        }else{
            this.getConsigneeInfo();
        };
    },

    //查询收货人默认地址
    getConsigneeInfo() {
        consignee_Info({ userId: this.data.userInfo.id }).then(res => {
            this.setData({ consigneeData: res.data.data });
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    //地址框点击事件
    addressTap() {
        wx.navigateTo({
            url: '/pagesShangping/pages/address/index',
        });
    },

    //提交按钮点击事件
    submitOrder() {
        this.setData({ buttonStates: true });
        if (this.data.consigneeData) {
            const arr = this.data.list.map(item => ({
                ...item,
                imageScale: item.imageScale.lenght != 0 ? item.imageScale.join(",") : ""
            }));
            const orderData = {
                shopOrderItems: arr,
                addressId: this.data.consigneeData.id,
                totalPrice: this.data.totalPrice,
                userId: this.data.userInfo.id
            };
            order_Create(orderData).then(res => {
                res.data.code === 200 ? this.callPayment(res.data.data) : wx.showToast({ title: res.data.msg, icon: 'none', duration: 2000 }); setTimeout(() => { ; this.setData({ buttonStates: false }); }, 2000);
            });
        } else {
            wx.showToast({
                icon: 'none',
                title: '请先去添加收货地址',
                duration: 2000
            });
            setTimeout(() => {
                this.setData({ buttonStates: false });
            }, 2000)
        };
    },

    //调用支付方法
    callPayment(order) {
        let obj = {
            body: '购买商品支付',
            outTradeNo: order.orderNumber,
            totalFee: order.totalPrice * 100,
            spbillCreateIp: order.spbillCreateIp,
            notifyUrl: `${baseUrl}/notify/order`,
            openid: getStorage("openId"),
            tradeType: "JSAPI",
        };
        unifiedOrderPlacement(obj).then(res => {
            const { appId, nonceStr, packageValue, paySign, signType, timeStamp } = res.data.data;
            wx.requestPayment({
                timeStamp: timeStamp,// 支签名时间，注意微信 jssdk 中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 tine5tamp 字船名需大写其中的S
                nonceStr: nonceStr,// 支付签名随机串，不长于 32 位
                package: packageValue,// 统一支付接口返回的prepay_id参数值，提交格式如: prepay_id=\*)
                signType: signType,// 微信支付V3的传入 RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
                paySign: paySign,
                "success": (res) => {
                    if (res.errMsg == "requestPayment:ok") {
                        paymentSuccessCallback({ orderNumber: obj.outTradeNo }).then(res => {
                            console.log(res.data, 'opopop');
                            if (res.data.code == 200) {
                                wx.showToast({
                                    title: "支付成功",
                                    icon: 'none',
                                    duration: 2000
                                });
                                setTimeout(() => {
                                    this.setData({ buttonStates: false });
                                    wx.navigateTo({
                                        url: '/pagesShangping/pages/paymentState/index?type=success',
                                    });
                                }, 2000);
                            };
                        });
                    } else {
                        wx.showToast({
                            title: res.errMsg,
                            icon: 'none',
                            duration: 2000
                        });
                    };
                },
                "fail": (res) => {
                    console.log(res, '报错了');
                    if (res.errMsg === 'requestPayment:fail cancel') {
                        wx.showToast({
                            title: '已取消支付',
                            icon: 'none',
                            duration: 2000
                        })
                    } else {
                        wx.showToast({
                            title: res.errMsg,
                            icon: 'none',
                            duration: 2000
                        });
                        setTimeout(() => {
                            wx.navigateTo({
                                url: '/pagesShangping/pages/paymentState/index?type=error',
                            });
                        }, 2000)
                    };
                    this.setData({ buttonStates: false });
                },
            });
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})